package com.crawData.utility;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 浏览器驱动实例工具类
 */
public   class  WebDriverUtility {

   private static ConcurrentHashMap<String,WebDriver> webDriverHashMap=new ConcurrentHashMap<>();


    /**
     * 获取谷歌浏览器驱动
     * @param keyWebDriver 要爬取的主页地址+手机号作为key
     * @return
     */
    public static WebDriver getWebDriver(String keyWebDriver) {
         //如果已经存在则直接返回
        if (webDriverHashMap.containsKey(keyWebDriver)) {
            return webDriverHashMap.get(keyWebDriver);
        }
        // 实例化 Chrome 驱动
        // 设置 Chrome 驱动路径
        String paht="D:\\dev\\chromedriver-win64_129.0.6668.101\\chromedriver-win64\\chromedriver.exe";
        System.setProperty("webdriver.chrome.driver", paht);
        // 初始化 Chrome 选项
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless");  // 添加无头模式
        options.addArguments("--disable-gpu");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-dev-shm-usage");

        // 禁用声音
        options.addArguments("--mute-audio");  // 静音
        options.addArguments("--autoplay-policy=no-user-gesture-required");

        // 其他有用的优化选项
        options.addArguments("--disable-notifications");  // 禁用通知
        options.addArguments("--disable-popup-blocking");  // 禁用弹窗
        options.addArguments("--disable-extensions");  // 禁用扩展
        options.addArguments("--disable-infobars");   // 禁用信息栏

         // 如果需要，可以设置代理
         // 获取并验证代理
        List<String> proxyList = getProxyList();
        for (String proxyAddress : proxyList) {
            if (validateProxy(proxyAddress)) {
                // 正确设置Chrome代理
                options.addArguments("--proxy-server=http://" + proxyAddress);
                break;
            }
        }
     
        // 使用 Chrome 选项初始化 WebDriver
        WebDriver driver = new ChromeDriver(options);
        webDriverHashMap.put(keyWebDriver,driver);
        return driver;
    }



    
    // 获取代理列表
    public static List<String> getProxyList() {
          List<String> proxyList = new ArrayList<>();
        try {
            // 使用89代理API获取代理列表
            String url = "http://api.89ip.cn/tqdl.html?api=1&num=10&port=&format=txt&tb=1&pro=&city=&loc=0";
            
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet request = new HttpGet(url);
                HttpResponse response = httpClient.execute(request);
                String content = EntityUtils.toString(response.getEntity());
                
                // 解析返回的代理地址
                String[] lines = content.split("\r?\n");
                for (String line : lines) {
                    line = line.trim();
                    if (line.matches("\\d+\\.\\d+\\.\\d+\\.\\d+:\\d+")) {
                        proxyList.add(line);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return proxyList;
    }

    // 验证代理是否可用
    public static boolean validateProxy(String proxyAddress) {
          try {
            String[] parts = proxyAddress.split(":");
            String host = parts[0];
            int port = Integer.parseInt(parts[1]);
            
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet request = new HttpGet("https://www.douyin.com");
                org.apache.http.HttpHost proxy = new org.apache.http.HttpHost(host, port);
                httpClient.getParams().setParameter(org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY, proxy);
                
                HttpResponse response = httpClient.execute(request);
                return response.getStatusLine().getStatusCode() == 200;
            }
        } catch (Exception e) {
            return false;
        }
    }
}
